/* 
Copyright (c) 2008 Dipartimento di Informatica ed Applicazioni �R.M.Capocelli�,
Universit� di Salerno (Italy) [vitsca@dia.unisa.it]

This software is part of CoFFEE, a framework for developing
and running cooperative distributed applications for facilitating
face2face interactions in classroom, developed in the European 
VI Framework project �LEAD: Technology-enhanced learning 
and problem-solving discussions: Networked learning environments 
in the classroom� (2005-2008)
(Contract no.: 028027).

All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html

Contributors:
   ISISLab, Dipartimento di Informatica ed Applicazioni �R.M.Capocelli�,
   Universit� di Salerno (Italy) [vitsca@dia.unisa.it]
 */
package lead.iexplorertool.server;


import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import lead.coreplugins.basic.LeadLogger.LeadLogger;
import lead.iexplorertool.actions.LocalDocsMessage;
import lead.iexplorertool.actions.SynchronousNavigationMessage;
import lead.iexplorertool.actions.AddressClickMessage;
import lead.iexplorertool.common.IExplorerBtnActionsConstants;
import lead.toolplugins.LEADMessage;
import lead.toolplugins.LEADToolUI;
import leadcoreutils.ConstantsUtils;
import leadcoreutils.ThemeUtils;

import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.internal.ole.win32.COM;
import org.eclipse.swt.internal.ole.win32.COMObject;
import org.eclipse.swt.internal.ole.win32.DISPPARAMS;
import org.eclipse.swt.internal.ole.win32.GUID;
import org.eclipse.swt.internal.ole.win32.IDispatch;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleEvent;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleListener;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.themes.ITheme;


public class IExplorerComposite extends LEADToolUI {

	/**
	 * the communication object
	 */
	private IExplorerService ieService;

	/**
	 * The chatArea panel
	 */
	private Composite browserAreaPanel;


	/**
	 * The label for the chat tool
	 */
	private CLabel labelToolName;

	/**
	 * The background color for chat tool.
	 */
	Color colorStd;
	/**
	 * The LEADTheme
	 */
	ITheme theme;

	/**
	 * Color Definition for the LEDATheme
	 */
	ColorRegistry colorRegistry;

	/**
	 * Font definition for the LEADTheme
	 */
	FontRegistry fontRegistry;

	final int OLECMDID_HIDETOOLBARS = 24;

	OleAutomation webBrowser = null;
	//Text textSearch = null;
	Combo textSearch = null;
	/**
	 * Check the set/reset synchronous  navigation
	 */
	int isSynchNavigation;
	/**
	 * Action of the click on the toolbar of the browser
	 */
	String buttonAction = ""; //$NON-NLS-1$

	/**
	 * A generic action on the toolbar
	 */
	String action = ""; //$NON-NLS-1$

	boolean isSynchronous = false; 
	boolean isLocalDocsShared = false;

	OleControlSite oleControlSite = null;

	Composite parent;
	private ToolItem itemFollowMe;
	private ToolItem itemLocalDocs;

	//web browser event control 
	static final int BeforeNavigate2 = 0xfa;
	static final int DocumentComplete = 0x103;
	static final int NavigateComplete2 = 0xfc;
	static final int ProgressChange = 0x6c;
	static final int NewWindow2 = 0xfb; // Fired when a new window should be created.
	static final int StatusTextChange = 0x66;

	//static final int NewWindow2 = 107;
	// Constants for WebBrowser CommandStateChange
	static final int DISPID_AMBIENT_DLCONTROL = -5512;

	static final int DLCTL_NO_SCRIPTS = 0x00000080;
	static final int DLCTL_NO_RUNACTIVEXCTLS = 0x00000200;
	static final int DLCTL_DOWNLOADONLY = 0x00000800;
	static final int DLCTL_NO_BEHAVIORS = 0x00008000;



	int globalDispatch;

	OleListener mouseListener;

	static final String ABOUT_BLANK = "about:blank";  //$NON-NLS-1$
	private ProgressBar    webProgress;
	private Label labelStatus;
	private Composite statusBarPanel; 
	final OleAutomation automation = null;

	//Icon of the toolbar
	private Image iconLocalDocsShared;
	private Image iconFollowMe;
	private Image iconNotFollowMe;


	private Logger logger = LeadLogger.getGlobalLogger(); 



	/**
	 * An address "http://etherpad.com/x9mYZHyo" : a collaborative text
	 */

	/**
	 * The class of the Internet Explorer browser
	 * @param parent
	 * @param service
	 * @param showArtifacts
	 */


	//Add the service as SharedOject
	public IExplorerComposite(Composite parent, IExplorerService service, boolean showArtifacts) {
		super(parent, showArtifacts);
		// TODO Auto-generated constructor stub
		theme = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme();

		colorRegistry = theme.getColorRegistry();
		fontRegistry = theme.getFontRegistry();

		colorStd =  colorRegistry.get(ThemeUtils.COLOR_TOOL_STD);

		setLayout(new FillLayout());
		ieService = service;
		init(this);
	}

	/**
	 * Create a the swt frame and fill it with the controls
	 * @param genericComposite
	 */
	/**
	 * @param toolsPanel
	 */
	private void init(IExplorerComposite toolsPanel) {
		///the new 
		parent = new Composite(toolsPanel, SWT.NONE);
		//parent.setLayout(new FormLayout());
		//parent = toolsPanel;

		GridLayout gl_bis = new GridLayout();
		parent.setLayout(gl_bis);

		// TODO Auto-generated method stub
		labelToolName = new CLabel(parent, SWT.NONE);
		//Image toolIcon = Activator.imageDescriptorFromPlugin("LeadCoreUtils","icons"+File.separator+"toolIcons"+File.separator+"server20x20"+File.separator+"chat.png").createImage(); 
		Image toolIcon = Activator.imageDescriptorFromPlugin("LeadCoreUtils","icons"+File.separator+"toolIcons"+File.separator+"server20x20"+File.separator+"browser.png").createImage();  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
		labelToolName.setImage(toolIcon);

		Composite controls = new Composite(parent, SWT.NONE);
		controls.setLayout(new FillLayout());

		GridLayout gl_Search = new GridLayout();
		gl_Search.numColumns = 1;
		gl_Search.makeColumnsEqualWidth = false;
		parent.setLayout(gl_Search);
		/**
		 * IE Browser
		 */
		browserAreaPanel = new Composite(parent,SWT.SCROLL_LINE | SWT.NONE);
		browserAreaPanel.setLayout(new FillLayout());

		GridData gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.verticalAlignment = GridData.FILL;
		browserAreaPanel.setLayoutData(gridData);
		

		//Creates a Web browser control. 
		String progID = "Shell.Explorer"; //$NON-NLS-1$
		OleFrame oleFrame = new OleFrame(browserAreaPanel,SWT.NONE);
		
		oleControlSite = new OleControlSite(oleFrame,SWT.NONE,"Shell.Explorer"); //$NON-NLS-1$
		webBrowser = new OleAutomation(oleControlSite);
		oleControlSite.doVerb(OLE.OLEIVERB_UIACTIVATE);

	
		// If you set this property, turn off script and image
		//Variant download = new Variant(DLCTL_NO_SCRIPTS);
		//oleControlSite.setSiteProperty(DISPID_AMBIENT_DLCONTROL, download);
		//oleControlSite.setSiteProperty(DLCTL_NO_SCRIPTS, download);

		//Progress bare and labelStatus
		statusBarPanel = new Composite(parent, SWT.NONE);
		GridLayout gl2 = new GridLayout();
		gl2.numColumns = 2;
		gl2.horizontalSpacing = 10;
		gl2.makeColumnsEqualWidth = true;
		statusBarPanel.setLayout(gl2);	
		
		
		labelStatus = new Label(statusBarPanel, SWT.LEFT);
		labelStatus.setText("                                                                       "); //$NON-NLS-1$
		labelStatus.setRedraw(true);
		labelStatus.setSize(900, 200);
		//labelStatus.setLayoutData(new GridData(GridData.FILL_BOTH));

		 
		/**
		 * Add a progress bar
		 */
		final int ProgressChange = 108; 
		//0x6C - obtained from the type library 
		final ProgressBar progressBar = new ProgressBar(statusBarPanel, SWT.BORDER | SWT.LEFT_TO_RIGHT); 
		oleControlSite.addEventListener(ProgressChange, new OleListener() {
			public void handleEvent(OleEvent event) {
				if (event.type != ProgressChange) return; 
				Variant progress = event.arguments[0]; 
				Variant maxProgress = event.arguments[1]; 
				if (progress == null || maxProgress == null) return; 
				progressBar.setMaximum(maxProgress.getInt()); 
				progressBar.setSelection(progress.getInt()); 
			} });
		 
		
		/**
		 * The web browser event
		 */
		OleListener listener = new OleListener() {
			public void handleEvent(OleEvent event) {
				int tmp = event.type;
				switch (event.type) {
				case  DocumentComplete : {
					//Variant download_ = new Variant(DLCTL_NO_RUNACTIVEXCTLS);
					String url = null;

					Variant varResult = event.arguments[1];
					url = varResult.getString();

					logger.info("BrowserTool: current url "+  url); //$NON-NLS-1$
					//Discard the empty page about:blank to be reloaded
					if(url.equals(ABOUT_BLANK))
						return;

					if(!url.equals(null)){
						//Send only htm file
						String [] extensions = new String [2];
						extensions[0] = "*.html"; //$NON-NLS-1$
						extensions[1] = "*.htm"; //$NON-NLS-1$

						String prefix = "http"; //$NON-NLS-1$
						String scriptPrefix = "javascript"; //$NON-NLS-1$
						if(url.startsWith(scriptPrefix))
							return;

						comboSearchDisplay(url);
					}

					break;
				}

				}

				Variant[] arguments = event.arguments;
				for (int i = 0; i < arguments.length; i++){
					
					arguments[i].dispose();
				}
			}
		};

		oleControlSite.addEventListener(DocumentComplete, listener);



		// Respond to StatusTextChange events by updating the Status Text label
		oleControlSite.addEventListener(StatusTextChange, new OleListener() {
			public void handleEvent(OleEvent event) {
				Variant statusText = event.arguments[0];
				if (statusText == null) return;
				String text = statusText.getString();
				if (text != null)
					labelStatus.setText(text);

			}
		});
		 
		browserAreaPanel.setFocus();
		oleFrame.pack();
		browserAreaPanel.pack();


		//Show the address of the home page
		webBrowser = new OleAutomation(oleControlSite);
		int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"}); //$NON-NLS-1$ //$NON-NLS-2$
		//read Home page from configuration File
		Variant[] address = new Variant[] {new Variant(ieService.getConf().get("homePageAddress"))}; //$NON-NLS-1$
		//Variant[] address = new Variant[] {new Variant("http://www.google.com")};
		webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});


		//ToolBar toolbar = new ToolBar(searchAreaPanel, SWT.BAR);
		ToolBar toolbar = new ToolBar(controls, SWT.BAR | SWT.LEFT);

		final ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
		itemBack.setText(Messages.getString("IExplorerComposite.BackBtn")); //$NON-NLS-1$
		itemBack.setToolTipText(Messages.getString("IExplorerComposite.BackBtnTooltip")); //$NON-NLS-1$
		Image iconBack = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/backward.gif"));  //$NON-NLS-1$
		itemBack.setImage(iconBack);

		final ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
		itemForward.setText(Messages.getString("IExplorerComposite.ForwardBtn")); //$NON-NLS-1$
		itemForward.setToolTipText(Messages.getString("IExplorerComposite.ForwardTooltip")); //$NON-NLS-1$
		Image iconForward = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/forward.gif"));  //$NON-NLS-1$
		itemForward.setImage(iconForward);

		ToolItem itemSeparator = new ToolItem(toolbar, SWT.SEPARATOR );

		textSearch = new Combo(toolbar, SWT.BORDER | SWT.SINGLE);
		//textSearch.setSize(200, 30);
		//textSearch.setBounds(100, 170, 200, 65);
		textSearch.setBounds(100, 170, 100, 65);


		itemSeparator.setWidth(textSearch.getBounds().width);
		itemSeparator.setControl(textSearch);


		//read form configuration url of Home page
		textSearch.setText(ieService.getConf().get("homePageAddress")); //$NON-NLS-1$
		textSearch.setToolTipText(ieService.getConf().get("homePageAddress")); //$NON-NLS-1$
		buttonAction = IExplorerBtnActionsConstants.HOME_BTN;


		final ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
		itemRefresh.setText(Messages.getString("IExplorerComposite.RefreshBtn")); //$NON-NLS-1$
		itemRefresh.setToolTipText(Messages.getString("IExplorerComposite.RefreshBtnTooltip")); //$NON-NLS-1$
		Image iconRefresh = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/refresh.gif"));  //$NON-NLS-1$
		itemRefresh.setImage(iconRefresh);

		final ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
		itemStop.setText(Messages.getString("IExplorerComposite.StopBtn")); //$NON-NLS-1$
		itemStop.setToolTipText(Messages.getString("IExplorerComposite.StopBtnTooltip")); //$NON-NLS-1$
		Image iconStop = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/stop.gif"));  //$NON-NLS-1$
		itemStop.setImage(iconStop);

		final ToolItem itemGoHome = new ToolItem(toolbar, SWT.PUSH);
		itemGoHome.setText(Messages.getString("IExplorerComposite.HomeBtn")); //$NON-NLS-1$
		Image iconHome = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/home.gif"));  //$NON-NLS-1$
		itemGoHome.setImage(iconHome);


		/**
		 * "Local docs mode " => Shared ppt file 
		 */
		itemLocalDocs = new ToolItem(toolbar, SWT.CHECK);
		itemLocalDocs.setText(Messages.getString("IExplorerComposite.LocalDocs_Btn"));  //$NON-NLS-1$
		iconLocalDocsShared = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/localDocs_btn.gif")); //$NON-NLS-1$
		itemLocalDocs.setImage(iconLocalDocsShared);
		itemLocalDocs.setSelection(false);


		ToolItem separator = new ToolItem(toolbar, SWT.SEPARATOR);

		itemFollowMe = new ToolItem(toolbar, SWT.CHECK);
		itemFollowMe.setText(Messages.getString("IExplorerComposite.FollowMeBtn")); //$NON-NLS-1$
		Image iconFollowMe = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/button_nok.png"));  //$NON-NLS-1$
		itemFollowMe.setImage(iconFollowMe);
		itemFollowMe.setSelection(false);


		itemFollowMe.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {

				if(itemFollowMe.getSelection()){
					//asynchronous  modality
					isSynchronous = true; 
				}
				else{
					//named modality
					isSynchronous = false; 
				}
				synchModeSend(isSynchronous);
			}
		});


		itemLocalDocs.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {

				if(itemLocalDocs.getSelection()){
					//shared modality
					isLocalDocsShared = true; 
				}
				else{
					//not shared modality
					isLocalDocsShared = false; 
				}
				try {
					localDocs(isLocalDocsShared);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		});

		textSearch.addListener(SWT.DefaultSelection, new Listener () {
			public void handleEvent (Event e) {
				String stringText = textSearch.getText();


				int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"}); //$NON-NLS-1$ //$NON-NLS-2$
				//read Home page from configuration File
				Variant[] address = new Variant[] {new Variant(stringText)};
				webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});

			}


		});


		textSearch.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				String stringText = textSearch.getText();

				int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"}); //$NON-NLS-1$ //$NON-NLS-2$
				//read Home page from configuration File
				Variant[] address = new Variant[] {new Variant(stringText)};
				webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});
			}
		});

		Listener toolbarListener = new Listener() {
			public void handleEvent(Event event) {
				ToolItem item = (ToolItem) event.widget;
				if (item == itemBack){
					int[] goBackIDs = webBrowser.getIDsOfNames(new String[]{"GoBack"}); //$NON-NLS-1$
					int dispIdMember = goBackIDs[0];

					Variant pVarResult = webBrowser.invoke(dispIdMember);

					buttonAction = IExplorerBtnActionsConstants.BACK_BTN;

				}
				else if (item == itemGoHome){
					int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"}); //$NON-NLS-1$ //$NON-NLS-2$
					//read Home page from configuration File
					Variant[] address = new Variant[] {new Variant(ieService.getConf().get("homePageAddress"))}; //$NON-NLS-1$
					int dispIdMember = browserIDs[0];
					webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});

					//String urlCurrent = ieService.getConf().get(Messages.getString("IExplorerComposite.42")); //$NON-NLS-1$
					String urlCurrent = ieService.getConf().get("homePageAddress"); //$NON-NLS-1$
					//Update of the tooltip
					itemGoHome.setToolTipText(urlCurrent);
					textSearch.setText(urlCurrent);


					buttonAction = IExplorerBtnActionsConstants.HOME_BTN;

				}
				else if (item == itemForward){
					int[] forwardIDs = webBrowser.getIDsOfNames(new String[]{"GoForward"}); //$NON-NLS-1$
					int dispIdMember = forwardIDs[0];
					Variant pVarResult = webBrowser.invoke(dispIdMember);
					buttonAction = IExplorerBtnActionsConstants.FORWARDS_BTN;

				}
				else if (item == itemStop){
					int[] forwardIDs = webBrowser.getIDsOfNames(new String[]{"Stop"}); //$NON-NLS-1$
					int dispIdMember = forwardIDs[0];
					Variant pVarResult = webBrowser.invoke(dispIdMember);
					buttonAction = IExplorerBtnActionsConstants.STOP_BTN;
				}
				else if (item == itemRefresh){
					//Reload
					int[] forwardIDs = webBrowser.getIDsOfNames(new String[]{"Refresh"}); //$NON-NLS-1$
					int dispIdMember = forwardIDs[0];
					Variant pVarResult = webBrowser.invoke(dispIdMember);
					buttonAction = IExplorerBtnActionsConstants.REFRESH_BTN;
				}
			}
		};

		itemGoHome.addListener(SWT.Selection, toolbarListener);
		itemBack.addListener(SWT.Selection, toolbarListener);
		itemForward.addListener(SWT.Selection, toolbarListener);
		itemRefresh.addListener(SWT.Selection, toolbarListener);
		itemStop.addListener(SWT.Selection, toolbarListener);

		//Label of the tool
		GridData gdLblToolName = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
		labelToolName.setLayoutData(gdLblToolName);
		labelToolName.setText(Messages.getString("IExplorerComposite.LabelToolName")); //$NON-NLS-1$

		// IWebBrowser
		final OleAutomation webBrowser = new OleAutomation(oleControlSite);
		int[] readyStateRgdispid = webBrowser.getIDsOfNames(new String[]{"ReadyState"}); //$NON-NLS-1$
		final int READYSTATE = readyStateRgdispid[0];

		createStatusArea();
		browserAreaPanel.setFocus();
		oleFrame.pack();
		browserAreaPanel.pack();
		webBrowser.dispose();
		applyTheme();

	}

	private void createStatusArea() {
		// TODO Auto-generated method stub
		// Respond to StatusTextChange events by updating the Status Text label
		oleControlSite.addEventListener(StatusTextChange, new OleListener() {
			public void handleEvent(OleEvent event) {
				Variant statusText = event.arguments[0];
				if (statusText == null) return;
				String text = statusText.getString();
				if (text != null)
					labelStatus.setText(text);

			}
		});
	}


	private void comboSearchDisplay(final String urlCurrent) {
		// TODO Auto-generated method stub
		/**
		 * Combo of  the navigated address
		 */
		final String addressCurrent = urlCurrent;
		final Display d =PlatformUI.getWorkbench().getDisplay();
		d.asyncExec(new Runnable(){
			public void run() {
				textSearch.setText(urlCurrent);
				textSearch.setToolTipText(urlCurrent);

				//textSearch.add(addressCurrent);
				String[] urlList = textSearch.getItems();
				Boolean isPresent = false;
				for(int i = 0; i< urlList.length; i++){
					String tmp = urlList[i];

					if(	urlList[i].equals(addressCurrent))
						isPresent = true;
				}
				if(!isPresent)
					textSearch.add(addressCurrent);
				try {
					logger.info("Browser Tool: Msg to send " + urlCurrent); //$NON-NLS-1$
					sendUrlBrowserAction(buttonAction, urlCurrent, isSynchronous);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}



	private void applyTheme() {
		// TODO Auto-generated method stub
		ThemeUtils.applyTheme(theme, colorRegistry.get(ThemeUtils.COLOR_BKG_TOOL), this);
		labelToolName.setFont(fontRegistry.get(ThemeUtils.FONT_TOOL_NAME));
		layout();
	}

	@Override
	public void layoutUI() {
		// TODO Auto-generated method stub
		layout();
	}
	/**
	 * Tracing of address when click  
	 * @param isSynchronous2 
	file:///C:/Users/Pina/Desktop/Prova/PD-04-0708-IPC_file/frame.htm */
	public void sendUrlBrowserAction(String actionBrowser, String address, boolean isSynchronous2) throws IOException{
		if (address.equals("")) //$NON-NLS-1$
			return;
		ieService.sendUrlBrowserSynchAction(actionBrowser, address, isSynchronous);
	}

	/**
	 * Tracing of address in the synchronous mode
	 */
	public void sendUrlBrowserSyncAction(AddressClickMessage urlMsg){
		final String syncAddress = urlMsg.getAddress();

		Display d = PlatformUI.getWorkbench().getDisplay();
		d.syncExec(new Runnable(){
			public void run() {
				textSearch.setText(syncAddress);
				textSearch.setToolTipText(syncAddress);

				webBrowser = new OleAutomation(oleControlSite);
				int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"}); //$NON-NLS-1$ //$NON-NLS-2$
				//read Home page from configuration File
				Variant[] address = new Variant[] {new Variant(syncAddress)};
				webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});
				return;
			}
		});

	}
	/**
	 * Send information to the clients about awareness for synchronous modality (Follow-me):
	 * changing the "anonymous" attribute during the executing of the current step. 
	 * @param check : 
	 */
	public void synchModeSend(final boolean  isSynchronous) {

		this.isSynchronous = isSynchronous;

		disableFollowMeMode(isSynchronous);

		SynchronousNavigationMessage synchrMsg = new SynchronousNavigationMessage();
		synchrMsg.setIsSynchronousNavigation(isSynchronous);

		//send synch navigation
		LEADMessage lcmsg = new LEADMessage(ieService, ieService.getIdentifier(), synchrMsg);
		lcmsg.setBroadcast(true);
		try {
			ieService.sendMessage(lcmsg);
		} catch (IOException e) {
			e.printStackTrace();
		}


		final Display d =PlatformUI.getWorkbench().getDisplay();
		d.asyncExec(new Runnable(){
			public void run() {
				//Send address to all clients
				String currentAddress = textSearch.getText();
				buttonAction = IExplorerBtnActionsConstants.FOLLOW_ME_BTN;
				try {
					ieService.sendUrlBrowserSynchAction(buttonAction, currentAddress, isSynchronous);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


			}
		});



	}



	/**
	 * Send information to the clients about awareness for shared modality the local docs of the teacher:
	 * changing the "isShared" attribute during the executing of the current step. 
	 * @param check : 
	 */
	public void localDocs(final boolean  isShared) throws IOException {
		final Display d =PlatformUI.getWorkbench().getDisplay();
		d.asyncExec(new Runnable(){
			public void run() {
				//The address of the http server  
				String httpServerAddress = ieService.getServerHttpAddress();

				//setting address search with the folder with ppt files
				textSearch.setText(httpServerAddress); 
				textSearch.setToolTipText(httpServerAddress); 

				int[] browserIDs = webBrowser.getIDsOfNames(new String[]{"Navigate","URL"});  //$NON-NLS-1$ //$NON-NLS-2$
				Variant[] address = new Variant[] {new Variant(httpServerAddress)};
				webBrowser.invoke(browserIDs[0],address,new int[]{browserIDs[1]});

				LocalDocsMessage sharedPPTMsg = new LocalDocsMessage();
				sharedPPTMsg.setUser(ConstantsUtils.TEACHER);
				sharedPPTMsg.setIsSharedLocalDocs(isShared);
				sharedPPTMsg.setHttphServerAddress(httpServerAddress);



				ieService.sendHttpServerAddressAction(sharedPPTMsg);
			}
		});
	}

	private static String getTypeName(int type) {
		switch (type) {
		case OLE.VT_BOOL:
			return "boolean"; //$NON-NLS-1$
		case OLE.VT_R4:
			return "float"; //$NON-NLS-1$
		case OLE.VT_R8:
			return "double"; //$NON-NLS-1$
		case OLE.VT_I4:
			return "int"; //$NON-NLS-1$
		case OLE.VT_DISPATCH:
			return "IDispatch"; //$NON-NLS-1$
		case OLE.VT_UNKNOWN:
			return "IUnknown"; //$NON-NLS-1$
		case OLE.VT_I2:
			return "short"; //$NON-NLS-1$
		case OLE.VT_BSTR:
			return "String"; //$NON-NLS-1$
		case OLE.VT_VARIANT:
			return "Variant"; //$NON-NLS-1$
		case OLE.VT_CY:
			return "Currency"; //$NON-NLS-1$
		case OLE.VT_DATE:
			return "Date"; //$NON-NLS-1$
		case OLE.VT_UI1:
			return "unsigned char"; //$NON-NLS-1$
		case OLE.VT_UI4:
			return "unsigned int"; //$NON-NLS-1$
		case OLE.VT_USERDEFINED:
			return "UserDefined"; //$NON-NLS-1$
		case OLE.VT_HRESULT:
			return "int"; //$NON-NLS-1$
		case OLE.VT_VOID:
			return "void"; //$NON-NLS-1$

		case OLE.VT_BYREF | OLE.VT_BOOL:
			return "boolean *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_R4:
			return "float *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_R8:
			return "double *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_I4:
			return "int *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_DISPATCH:
			return ""; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_UNKNOWN:
			return ""; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_I2:
			return ""; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_BSTR:
			return ""; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_VARIANT:
			return ""; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_CY:
			return "Currency *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_DATE:
			return "Date *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_UI1:
			return "unsigned char *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_UI4:
			return "unsigned int *"; //$NON-NLS-1$
		case OLE.VT_BYREF | OLE.VT_USERDEFINED:
			return "UserDefined *"; //$NON-NLS-1$
		}
		return "unknown " + type; //$NON-NLS-1$
	}

	private static String getDirection(int direction) {
		String dirString = ""; //$NON-NLS-1$
		boolean comma = false;
		if ((direction & OLE.IDLFLAG_FIN) != 0) {
			dirString += "in"; //$NON-NLS-1$
			comma = true;
		}
		if ((direction & OLE.IDLFLAG_FOUT) != 0) {
			if (comma)
				dirString += ", "; //$NON-NLS-1$
			dirString += "out"; //$NON-NLS-1$
			comma = true;
		}
		if ((direction & OLE.IDLFLAG_FLCID) != 0) {
			if (comma)
				dirString += ", "; //$NON-NLS-1$
			dirString += "lcid"; //$NON-NLS-1$
			comma = true;
		}
		if ((direction & OLE.IDLFLAG_FRETVAL) != 0) {
			if (comma)
				dirString += ", "; //$NON-NLS-1$
			dirString += "retval"; //$NON-NLS-1$
		}

		return dirString;
	}

	/*private static String getInvokeKind(int invKind) {
		switch (invKind) {
		case OLE.INVOKE_FUNC:
			return Messages.getString("IExplorerComposite.94"); //$NON-NLS-1$
		case OLE.INVOKE_PROPERTYGET:
			return Messages.getString("IExplorerComposite.95"); //$NON-NLS-1$
		case OLE.INVOKE_PROPERTYPUT:
			return Messages.getString("IExplorerComposite.96"); //$NON-NLS-1$
		case OLE.INVOKE_PROPERTYPUTREF:
			return Messages.getString("IExplorerComposite.97"); //$NON-NLS-1$
		}
		return Messages.getString("IExplorerComposite.98") + invKind; //$NON-NLS-1$
	}*/


	public OleAutomation getAutomation() {
		return webBrowser;
	}

	public void setAutomation(OleAutomation automation) {
		this.webBrowser = automation;
	}

	public String sendTextSearch_(String stringText) {
		/*try {
			//ieService.sendGenericMessage(stringText);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return stringText;

	}

	public OleAutomation getWebBrowser() {
		return webBrowser;
	}

	public void setWebBrowser(OleAutomation webBrowser) {
		this.webBrowser = webBrowser;
	}

	public void disableWidget() {
		// TODO Auto-generated method stub
		final LEADToolUI mainComposite=this; 
		final Display d =PlatformUI.getWorkbench().getDisplay();
		d.asyncExec(new Runnable(){
			public void run() {
				if (! ieService.isOwn()){
					mainComposite.setVisible(isShowArtifacts());
				}else {
					mainComposite.setVisible(true);
				}

				mainComposite.layoutUI();
			}
		});
	}

	/**
	 * Enable/Disable button of the  
	 */

	private void disableFollowMeMode(final Boolean isEnable){


		final Display d =PlatformUI.getWorkbench().getDisplay();
		d.asyncExec(new Runnable(){
			public void run() {
				if(isEnable){
					iconFollowMe = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/button_ok.png"));  //$NON-NLS-1$
					itemFollowMe.setImage(iconFollowMe);
				}
				else{
					iconNotFollowMe = new Image(parent.getDisplay(), getClass().getResourceAsStream("/icons/button_nok.png"));  //$NON-NLS-1$
					itemFollowMe.setImage(iconNotFollowMe);
				}
			}
		});

	}


}


//EventDispatch implements a simple IDispatch interface which will be called
//when the event is fired.
class EventDispatch {
	private COMObject iDispatch;

	private int refCount = 0;

	private int eventID;

	final static int onhelp = 0x8001177d;

	final static int onclick = 0x80011778;

	final static int ondblclick = 0x80011779;

	final static int onkeyup = 0x80011776;

	final static int onkeydown = 0x80011775;

	final static int onkeypress = 0x80011777;

	final static int onmouseup = 0x80011773;

	final static int onmousedown = 0x80011772;

	final static int onmousemove = 0x80011774;

	final static int onmouseout = 0x80011771;

	final static int onmouseover = 0x80011770;

	final static int onreadystatechange = 0x80011789;

	final static int onafterupdate = 0x80011786;

	final static int onrowexit = 0x80011782;

	final static int onrowenter = 0x80011783;

	final static int ondragstart = 0x80011793;

	final static int onselectstart = 0x80011795;

	EventDispatch(int eventID) {
		this.eventID = eventID;
		createCOMInterfaces();
	}

	int getAddress() {
		return iDispatch.getAddress();
	}

	private void createCOMInterfaces() {
		iDispatch = new COMObject(new int[] { 2, 0, 0, 1, 3, 4, 8 }) {
			/*public int method0(int[] args) {
				return QueryInterface(args[0], args[1]);
			}
			 */
			public int method1(int[] args) {
				return AddRef();
			}

			public int method2(int[] args) {
				return Release();
			}

			// method3 GetTypeInfoCount - not implemented
			// method4 GetTypeInfo - not implemented
			// method5 GetIDsOfNames - not implemented
			public int method6(int[] args) {
				return Invoke(args[0], args[1], args[2], args[3], args[4],
						args[5], args[6], args[7]);
			}
		};
	}

	private void disposeCOMInterfaces() {
		if (iDispatch != null)
			iDispatch.dispose();
		iDispatch = null;

	}

	private int AddRef() {
		refCount++;
		return refCount;
	}

	private int Invoke(int dispIdMember, int riid, int lcid, int dwFlags,
			int pDispParams, int pVarResult, int pExcepInfo, int pArgErr) {
		switch (eventID) {
		case onhelp:

			break;
		case onclick:
			/*System.out.println("******> 1");
			DISPPARAMS params = new DISPPARAMS();
			COM.MoveMemory(params, pDispParams, DISPPARAMS.sizeof);
			Variant variant = Variant.win32_new(params.rgvarg);
			OleAutomation event = variant.getAutomation();
			variant.dispose();

			int[] rgdispid = event.getIDsOfNames(new String[] {
			"srcElement" });
			dispIdMember = rgdispid[0];
			Variant result = event.getProperty(dispIdMember);
			event.dispose();

			OleAutomation element = result.getAutomation();
			result.dispose();
			rgdispid = element.getIDsOfNames(new String[] {
			"outerHtml" });
			dispIdMember = rgdispid[0];
			result = element.getProperty(dispIdMember);
			element.dispose();
			System.out.println("******>2"+ result.getString());
			result.dispose();

			 */
		case ondblclick:
			break;
		case onkeyup:

			break;
		case onkeydown:

			break;
		case onkeypress:

			break;
		case onmouseup:

			break;
		case onmousedown:

			break;
		case onmousemove:

			break;
		case onmouseout:

			break;
		case onmouseover:

			break;
		case onreadystatechange:

			break;
		case onafterupdate:

			break;
		case onrowexit:

			break;
		case onrowenter:

			break;
		case ondragstart:

			break;
		case onselectstart:

			break;
		}
		return COM.S_OK;
	}

	private int QueryInterface(int riid, int ppvObject) {
		if (riid == 0 || ppvObject == 0)
			return COM.E_INVALIDARG;
		GUID guid = new GUID();
		COM.MoveMemory(guid, riid, GUID.sizeof);

		if (COM.IsEqualGUID(guid, COM.IIDIUnknown)
				|| COM.IsEqualGUID(guid, COM.IIDIDispatch)) {
			COM.MoveMemory(ppvObject, new int[] { iDispatch.getAddress() }, 4);
			AddRef();
			return COM.S_OK;
		}
		COM.MoveMemory(ppvObject, new int[] { 0 }, 4);
		return COM.E_NOINTERFACE;
	}

	int Release() {
		refCount--;
		if (refCount == 0) {
			disposeCOMInterfaces();
		}
		return refCount;
	}


}
